/**
 * 建筑管理
 */
import * as React from "react";
import {
  Row,
  Col,
  Tabs,
  Card,
  Modal,
  Tree,
  Skeleton,
  Input,
  Table,
  Button,
  Spin,
} from "antd";
import { observer } from "mobx-react";
import ConstructionTreeTable from "./compontents/ConstructionTreeTable";
import { cloneDeep } from "lodash";
import { SyncOutlined, SearchOutlined } from "@ant-design/icons";
import {
  listToAntdTreeSelectTreeData,
  ergodicListAddIdToKey,
  arrRemoveItem,
  listAddTreeId,
} from "../../../../utils/common";
import {
  getfindFilesBuildList,
  // getBoundDevices,
  getUnboundDevices,
  // boundDevices,
  // unBoundDevices,
  getDevicesByBuildId,
  rebindBatch,
  unbindBatch,
} from "../ServeApi";
import { AjaxData } from "../../../../data/interface/publicInterface";
import IconFont from "../../../../assets/ICON";
import "./index.less";

const { TabPane } = Tabs;
export interface ConstructionManageProps {}

export interface ConstructionManageState {}

@observer
class ConstructionManage extends React.Component<
  ConstructionManageProps,
  ConstructionManageState
> {
  state = {
    selectedRowKeys: [],
    searchValue: "",
    loading: false,
  };
  private type = 1; //水电类型
  private bound = 1; //是否绑定
  private TreeSelectTreeData: any = null; //数据tree
  private orgid = 0;
  private timer: any = null;
  private selectKey: any = []; //选中的设备
  private dataSouce: any[] = [];
  private pageIndex: number = 1;
  private pageSize: number = 10;
  private total: number = 0;
  private iptText: string = "";
  private columns = [
    {
      title: "设备编号",
      dataIndex: "no",
      key: "no",
    },
    {
      title: "设备名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "设备地址",
      dataIndex: "devAddr",
      key: "devAddr",
    },
    {
      title: "能源类型",
      dataIndex: "aaa",
      key: "aaa",
      render: (text, record) => {
        return <>{this.type === 1 ? "电" : "水"}</>;
      },
    },
    {
      title: "状态",
      dataIndex: "bbb",
      key: "bbb",
      render: (text, record) => {
        return <>{this.bound === 1 ? "绑定" : "未绑定"}</>;
      },
    },
  ];
  render() {
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onSelect: this.onSelectChange,
      onSelectAll: this.onSelectAll,
    };
    return (
      <>
        <div className="ConstructionManage">
          <Tabs defaultActiveKey="1">
            <TabPane tab="建筑管理" key="1">
              <Row>
                <Col span={24}>
                  <ConstructionTreeTable />
                </Col>
              </Row>
            </TabPane>
            <TabPane tab="绑定设备" key="2">
              <Row>
                <Col span={4}>
                  <Card
                    title="建筑信息"
                    extra={<SyncOutlined />}
                    style={{ height: 700 }}
                  >
                    <div className="treeList">
                      <Input
                        placeholder="请输入关键字查询"
                        suffix={
                          <SearchOutlined
                            onClick={() => {
                              this.getFilesBuildList(this.state.searchValue);
                            }}
                          />
                        }
                        style={{ background: "#EEF2FE" }}
                        value={this.state.searchValue}
                        onChange={(e: any) => {
                          this.setState({ searchValue: e.target.value });
                        }}
                      />
                      {this.TreeSelectTreeData ? (
                        <Tree
                          className="draggable-tree"
                          // checkable
                          draggable
                          blockNode
                          treeData={this.TreeSelectTreeData}
                          defaultExpandAll={true}
                          onSelect={(selectedKeys, e: any) => {
                            this.getOrgId(e.node.id);
                          }}
                        />
                      ) : (
                        <Skeleton active />
                      )}
                    </div>
                  </Card>
                </Col>
                <Col span={20} style={{ paddingLeft: 12 }}>
                  <div className="rowcon_body">
                    <div className="bare_body">
                      <div className="changeType_btn d_inlineFlex">
                        <Button
                          className="left"
                          type={this.bound === 1 ? "primary" : "default"}
                          onClick={() => {
                            this.changeBound(1);
                            this.forceUpdate();
                          }}
                        >
                          已绑定
                        </Button>
                        <Button
                          className="right"
                          type={this.bound === 2 ? "primary" : "default"}
                          onClick={() => {
                            this.changeBound(2);
                            this.forceUpdate();
                          }}
                        >
                          未绑定
                        </Button>
                      </div>
                      <div className="f-right" style={{ textAlign: "right" }}>
                        <Input.Group compact>
                          <Input
                            style={{ width: "60%" }}
                            placeholder="关键字搜索"
                            onChange={(e) => {
                              this.iptText = e.target.value;
                              this.forceUpdate();
                            }}
                            value={this.iptText}
                            bordered={false}
                            prefix={
                              <SearchOutlined
                                onClick={() => {
                                  this.keyWordSearch(this.iptText);
                                }}
                              />
                            }
                          />

                          {this.bound === 2 ? (
                            <Button
                              type="primary"
                              icon={<IconFont type="icon_bangding" />}
                              onClick={() => {
                                this.bingDev();
                              }}
                            >
                              绑定
                            </Button>
                          ) : (
                            <Button
                              type="primary"
                              icon={<IconFont type="icon_jiebang" />}
                              onClick={() => {
                                this.unBindDev();
                              }}
                              style={{
                                background: "#F4990D",
                                borderColor: "#F4990D",
                                marginLeft: 10,
                              }}
                            >
                              解绑
                            </Button>
                          )}
                        </Input.Group>
                      </div>
                    </div>
                    <div style={{ height: 635 }}>
                      <Spin spinning={this.state.loading}>
                        <Table
                          columns={this.columns}
                          dataSource={this.dataSouce}
                          rowSelection={rowSelection}
                          pagination={{
                            pageSize: this.pageSize,
                            current: this.pageIndex,
                            total: this.total,
                            onChange: (page: number) => {
                              this.pageIndex = page;
                              this.getPream();
                            },
                          }}
                          // scroll={{ y: 500 }}
                          style={{ paddingTop: 16 }}
                        ></Table>
                      </Spin>
                    </div>
                  </div>
                </Col>
              </Row>
            </TabPane>
          </Tabs>
        </div>
      </>
    );
  }
  componentWillMount() {
    this.getFilesBuildList("");
  }
  unBindDev() {
    let _this = this;
    if (!this.orgid) {
      Modal.warning({ title: "请选择建筑" });
      return false;
    }
    if (this.state.selectedRowKeys.length < 1) {
      Modal.warning({ title: "请选中设备" });
      return false;
    }
    let pream = {
      buildId: this.orgid,
      deviceIds: this.state.selectedRowKeys,
    };
    unbindBatch(JSON.stringify(pream)).then((rtn: any) => {
      if (rtn) {
        let res: AjaxData = rtn;
        if (res.success) {
          _this.getPream();
        } else {
          Modal.error({ title: res.message });
        }
      }
    });
  }
  bingDev() {
    let _this = this;
    if (!this.orgid) {
      Modal.warning({ title: "请选择建筑" });
      return false;
    }
    if (this.state.selectedRowKeys.length < 1) {
      Modal.warning({ title: "请选中设备" });
      return false;
    }
    let pream = {
      buildId: this.orgid,
      deviceIds: this.state.selectedRowKeys,
    };
    rebindBatch(JSON.stringify(pream)).then((rtn: any) => {
      if (rtn) {
        if (rtn.success) {
          _this.getPream();
        } else {
          Modal.error({ title: rtn.message });
        }
      }
    });
  }
  /**请求部分 */
  //请求建筑数据
  async getFilesBuildList(str) {
    let _this = this;
    let pream = {
      name: str,
    };
    let prom: any = await getfindFilesBuildList(JSON.stringify(pream)).catch(
      (err) => {
        if (err) {
          console.log(err);
        }
      }
    );
    if (prom) {
      let res: AjaxData = prom;
      if (res.success) {
        this.TreeSelectTreeData = listToAntdTreeSelectTreeData(
          listAddTreeId(res.data)
        );
        this.forceUpdate();
      } else {
        Modal.warning({
          title: res.message,
          onOk() {
            _this.setState({ loading: false });
          },
        });
      }
    }
  }
  //请求已绑定数据
  async getBindList(pream: any) {
    let _this = this;
    let prom: any = await getDevicesByBuildId(JSON.stringify(pream)).catch(
      (err) => {
        console.log(err);
      }
    );
    if (prom) {
      let res: AjaxData = prom;
      if (res.success) {
        this.dataSouce = res.data.map((item) => {
          item.key = item.id;
          return item;
        });
        this.setState({ loading: false });
        this.forceUpdate();
      } else {
        Modal.error({
          title: res.message,
          onOk() {
            _this.setState({ loading: false });
          },
        });
      }
    }
  }
  //请求未绑定数据
  async getUnbindList(pream: any) {
    let _this = this;

    try {
      this.setState({ loading: true });
      const res: any = await getUnboundDevices(JSON.stringify(pream));
      const json: AjaxData = res;
      if (json.success) {
        _this.dataSouce = ergodicListAddIdToKey(json.data.records);
        _this.total = json.data.total;
        _this.setState({ loading: false });
        _this.forceUpdate();
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk() {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (e) {
      Modal.error({
        title: `请求出错,请检查设备链接和网络情况。`,
      });
      _this.setState({ loading: false });
      console.error(e);
    }
    // this.forceUpdate();
  }
  onSelectAll = (selected, selectedRows, changeRows) => {
    let seleArr: any = cloneDeep(this.state.selectedRowKeys);

    if (selected) {
      changeRows.map((item) => {
        seleArr.push(item.id);
        seleArr = Array.from(new Set(seleArr));
        return item;
      });
    } else {
      changeRows.map((item) => {
        seleArr = arrRemoveItem(item.id, seleArr);
        return item;
      });
    }
    this.setState({ selectedRowKeys: seleArr });
  };
  onSelectChange = (record, selected) => {
    let seleArr: any = cloneDeep(this.state.selectedRowKeys);

    if (selected) {
      //选中
      seleArr.push(record.id);
    } else {
      //取消
      seleArr = arrRemoveItem(record.id, seleArr);
    }
    this.setState({ selectedRowKeys: seleArr });
  };

  getType(type: number) {
    this.clearPream();
    this.type = type;
    this.getPream(); //更新请求
    this.forceUpdate();
  }
  getOrgId(id: number) {
    this.orgid = id;
    this.clearPream();
    this.getPream(); //更新请求
    this.forceUpdate();
  }
  changeBound(bound: number) {
    this.bound = bound;
    this.clearPream();
    this.getPream(); //更新请求
    this.forceUpdate();
  }
  keyWordSearch(key: string) {
    this.clearPream();
    this.getPream(); //更新请求
    this.forceUpdate();
  }
  clearPream() {
    this.pageIndex = 1;
    this.pageSize = 10;
    this.setState({ selectedRowKeys: [] });
    this.selectKey = []; //清空选中的设备
  }
  getPream() {
    let aa: any = null;
    aa = {
      BuildId: this.orgid,
      isBind: this.bound,
      device: this.iptText,
    };
    if (this.orgid) {
      this.setState({ loading: true });
      this.getBindList(aa);
    }
    console.log(aa);
  }
  getUpData() {
    // 简化写法
  }
}

export default ConstructionManage;
